package com.ray.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.google.appengine.repackaged.org.joda.time.field.DelegatedDateTimeField;
import com.ray.bean.CompanyBean;
import com.ray.bean.DepartmentBean;
import com.ray.bean.MaterialNameConfigBean;
import com.ray.bean.RoleBean;
import com.ray.bean.UserBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.PermissionMapper;
import com.ray.mapper.UserMapper;
import com.ray.pojo.MyUser;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.redis.RedisCache;
import com.ray.util.redis.RedisKey;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;


@Service
public class CompanyService {

	@Autowired
	CompanyMapper companyMapper;
	@Autowired
	UserService userService;
	@Autowired
	PermissionService permissionService;
	@Autowired
	PermissionMapper permissionMapper;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	WorkshopService workshopService;
    @Autowired
    ScheduleService scheduleService;


	/**
	 * 校验公司是否存在
	 * @param map
	 * @throws ServiceException
	 */
	public void checkCpnpany(Map map) throws ServiceException {
		CompanyBean companyBean=companyMapper.getCompanyByMap(map);
		if(null!=companyBean) {
			throw new ServiceException(ReturnStringUtil.COMPANY_ALREADY_EXCEPTION);
		}
	}


	/**
	 * 公司注册，生成默认部门与默认用户
	 * @param map
	 * @throws ServiceException
	 */
	public void registerCompany(Map map) throws ServiceException {
		this.checkCpnpany(map);
		if(!map.get("password").equals(map.get("passwordCheck"))) {
			throw new ServiceException(ReturnStringUtil.PASSWORD_NOTEQUAL_EXCEPTION);
		}
	    //创建公司
		CompanyBean companyBean=new CompanyBean();
		String companyName=map.get("companyName").toString();
		companyBean.setName(companyName);
		companyBean.setIsUpdate(0);//制单可输可选
		companyBean.setIsApprovalReport(0);//报工不需要审核
		companyBean.setType(Integer.parseInt(map.get("type").toString()));
		companyBean.setIsNeedCode(1);//需要验证码
		companyBean.setIsAutoApproval(1);
	    companyMapper.insertCompany(companyBean);
		companyBean=companyMapper.getCompanyByMap(map);
		//得到公司id
		int id=companyBean.getId();
//		创建用户
		UserBean userBean=new UserBean();
//		UserBean yeChaoBo=new UserBean();
		userBean.setCompany(companyBean.getName());//设置公司名
		userBean.setIsManager(1);//设置是否是创建人
		userBean.setPassword(map.get("password").toString());
		userBean.setPhone(map.get("phone").toString());
		userBean.setUserCard(map.get("registerUser").toString());//账号，默认与用户名相同
		userBean.setUserName(map.get("registerUser").toString());
		userBean.setStatus("开启");
		userService.insertUser(userBean);
		userBean=userService.getUserBean(userBean);
//		为用用户创建角色
		RoleBean roleBean=new RoleBean();
		String roleId=StringUtil.getUUID();
		roleBean.setCreateUser("admin");
		roleBean.setCompanyId(companyBean.getName());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String time=sdf.format(new Date());
		roleBean.setCreateTime(time);
		roleBean.setDescription("公司创建人");
		roleBean.setId(roleId);
		roleBean.setName("超级管理员");
		permissionService.addRole(roleBean);
//		赋予用户角色
		List<String> strList=new ArrayList<String>();
		strList.add(roleBean.getId());
	    permissionMapper.addUserRole(userBean.getId(),strList);
		
//		permissionService.addUserRole(userBean.getId(), strList);
//		permissionService.addUserRole(yeChaoBo.getId(), strList);
//		为此角色赋予最高权限
		List<String> perIdList=permissionService.getPermissionIdListNotPay();
		permissionService.addRolePermission(roleBean.getId(), perIdList);
		
		//插入公司信息记录
		companyMapper.insertCompanyInfo(companyBean);
		
        //发送消息
		String accessToken=weiXinService.getAccessToken(null); 
		JSONObject json=WeixinTemplateList.packJsonWatiApproval("有新的公司注册请尽快审核", "公司注册申请", userBean.getUserName(), userBean.getPhone(),time,"公司名称:"+userBean.getCompany()+"\n" , null, null, null, null, null, null, null, null);
		//nate
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw0_UhnWghEzp4DCHVZb23f8", WeiXinParamesUtil.watiApprovalTemplateID,WeiXinParamesUtil.messageLink+"?loginToken=o_THqw0_UhnWghEzp4DCHVZb23f8&pageType="+RedirectUrlUtil.APPROVAL_COMPANY, json, accessToken);
		//yechaobo                                
		WeixinTemplateSender.sendWechatmsgToUser("o_THqw0TJcxQLDEwiBFYh7xtaT18", WeiXinParamesUtil.watiApprovalTemplateID,WeiXinParamesUtil.messageLink+"?loginToken=o_THqw0TJcxQLDEwiBFYh7xtaT18&pageType="+RedirectUrlUtil.APPROVAL_COMPANY, json, accessToken);
	}


	//设置是否修改
	public void setCompany(Map map) {
		if(null!=map.get("approvalAllReport") && "true".equals(map.get("approvalAllReport").toString()) ) {
			workshopService.updateCompanySetToApprovalAllReport(map);
		}
		companyMapper.setCompany(map);
	}


	/**
	 * 获取公司信息
	 * @param map
	 * @return
	 */
	public CompanyBean getCompany(Map map) {
		return companyMapper.getCompany(map);
	}

	/**
	 * 设置部门入库方式
	 * @param jsonArray(参数)
	 * @throws ServiceException
	 */
	public void setDeptInWorkShopMode(Map map) {
		Assert.notNull(map.get("jsonArray"), "未获取到部门参数");
		String jsonArray=map.get("jsonArray").toString();
		JSONArray jsor=JSONArray.fromObject(jsonArray);
		List<DepartmentBean> list=(List<DepartmentBean>) JSONArray.toCollection(jsor, DepartmentBean.class);
		map.put("deptList", list);
		companyMapper.setDeptInWorkShopMode(map);
	}


	/**
	 * 获取所有公司
	 * companyName
	 * @param request
	 * @return
	 * @throws ServiceException
	 */
	public List<CompanyBean> getAllCompany(Map map) {
		return companyMapper.getAllCompany(map);
	}


	/**
	 * loginCompany
	 * 审核公司
	 * @param map
	 */
	public void approvalCompany(Map map) {
        String loginUserId=map.get("loginUserId").toString();
        Assert.isTrue("537".equals(loginUserId) || "566".equals(loginUserId),"没有权限审核");
        int status =Integer.parseInt(map.get("status").toString());
        //审核为付费用户
        if(1==status) {
        	 permissionMapper.setAdminPermission(map.get("companyName").toString());
        }else {
        	 //设置注册人自己审核自己的四个权限
        	permissionMapper.setDefaultApprval(map);
        }
        int row= companyMapper.apprlvalCompany(map);
        Assert.isTrue(row>0,ReturnStringUtil.UPDATE_ERROR);
	}


	/**
	 * 获取公司物料名称配置
	 * @param map
	 * @return
	 */
	public List<MaterialNameConfigBean> getMaterialConfig(Map map) {
		return companyMapper.getMaterialConfig(map);
	}


	/**
	 * 设置物料名称配置
	 * @param map
	 * @return
	 * jsonArray
	 * materialName  物料名称
	 * adJustInPrice 入库可调整单价范围
	 * adJustInCount 入库可调整数量
	 */
	public String  setMaterialConfig(Map map) {
		StringUtil.checkIsTrue(map, "jsonArray", "未获取到参数");
		String jsonStr = map.get("jsonArray").toString();
		JSONArray jsonArray=JSONArray.fromObject(jsonStr);
		List<MaterialNameConfigBean> list=(List<MaterialNameConfigBean>) JSONArray.toCollection(jsonArray, MaterialNameConfigBean.class);
		companyMapper.deleteMaterialConfig(map);
		if(list.size()>0) {
			map.put("list", list);
			int row =companyMapper.insertMaterialConfig(map);
		}
		return ReturnStringUtil.SET_SUCCESS;
	}


	/**
	 * @param map
	 * @return
	 */
	public List<Map> getCompanyUseDetail() {
		List<Map> list=(List<Map>) RedisCache.getDataFromRedis(RedisKey.COMPANY_USE_DETAIL);
		if(null==list) {
			list=scheduleService.setCompanyUseDetailToRedis();
		}
		return list;
	}


	public void updateComapnyPayEndClockTime(Map map) {
		// TODO Auto-generated method stub
		companyMapper.updateComapnyPayEndClockTime(map);
	}

}
